<template>
  <el-dialog title="配置数据源" :close-on-click-modal="false" :show-close="false" visible :close-on-press-escape="false"
    destroy-on-close>
    <el-form label-width="90px" ref="form" :model="basic">
      <el-form-item label="表单" prop="tableName" :rules="[{
            required: true,
            message: '请选择表单',
            trigger:'blur'
            }]">
        <el-select filterable v-model="basic.tableName" @change="changeTable" style="width:60%;">
          <el-option v-for="opt in tableOptions" :key="opt.value" :label="opt.label" :value="opt.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-button size="small" type="primary" style="marginBottom:10px;" @click="addTab()">
      添加级
    </el-button>
    <el-tabs v-model="editableTabsValue" type="card" @tab-remove="removeTab" :before-leave="changeTab">
      <el-tab-pane :key="item.name" v-for="(item, index) in editableTabs" :label="`${toChineseNumber(index+1)}级数据源`"
        :name="item.name" :closable="index===editableTabs.length-1">
        <el-button size="small" type="primary" style="marginBottom:10px;" @click="addDatasource()">
          添加数据源
        </el-button>
        <el-form :model="formData[index]" label-width="90px" ref="levelForm">
          <el-row :gutter="24">
            <el-col :span="12" v-for="(data, ind) in formData[index].datas" :key="ind">
              <el-form-item label="数据字段" :prop="`datas.${ind}.fieldName`" :rules="[{
            required: true,
            message: '请选择数据字段',
            trigger:'blur'
            }]">
                <el-select filterable v-model="data.fieldName" style="width:60%;">
                  <el-option v-for="opt in fieldOptions" :key="opt.value" :label="opt.label" :value="opt.value">
                  </el-option>
                </el-select>
                <el-button v-if="index === 0 && ind > 0" @click="removeDatasource(ind)" type="danger"
                  style="marginLeft:10px;">删除
                </el-button>
              </el-form-item>
              <el-form-item v-if="index > 0" label="父级字段" :prop="`datas.${ind}.parent`" :rules="[{
            required: true,
            message: '请选择数据字段',
            trigger:'blur'
            }]">
                <el-select filterable v-model="data.parent" style="width:60%;">
                  <el-option v-for="opt in getParent(index)" :key="opt.value" :label="opt.label" :value="opt.value">
                  </el-option>
                </el-select>
                <el-button v-if="index > 0 && ind > 0" @click="removeDatasource(ind)" type="danger"
                  style="marginLeft:10px;">删除
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer">
      <el-button type="primary" @click="handelConfirm">
        确定
      </el-button>
      <el-button @click="close">
        取消
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
  import {
    getAllFormName,
    getTableColumn
  } from '@/api/custom/formDesigner'
  import {
    toChineseNum
  } from '@/utils/toChineseNum'
  export default {
    props: ['fields', 'formName'],
    data() {
      return {
        editableTabsValue: '1',
        basic: {
          tableName: ''
        },
        formData: [],
        tableOptions: [],
        fieldOptions: [],
        editableTabs: [],
        tabIndex: 1
      }
    },
    mounted() {
      this.getTableName()
      this.tabIndex = this.fields.length + 1
      this.formData = [...this.fields]
      this.basic.tableName = this.formName
      this.formData.length > 0 && this.formData.map((item, index) => {
        if (index === 0) {
          this.editableTabsValue = item.name
        }
        this.editableTabs.push({
          name: item.name
        })
      })
      if (this.formName) {
        this.getFieldOption(this.formName)
      }
    },
    methods: {
      handelConfirm() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.formData.length === 0) {
              this.$message.error('请添加级')
            } else {
              if (Array.isArray(this.$refs.levelForm)) {
                this.$refs.levelForm[this.$refs.levelForm.length - 1].validate((valid) => {
                  if (valid) {
                    this.$emit('commit', this.formData, this.basic.tableName)
                    this.close()
                    return true
                  } else {
                    this.$message.error('请补全各级数据源')
                    return false
                  }
                })
              } else {
                this.$refs.levelForm.validate((valid) => {
                  if (valid) {
                    this.$emit('commit', this.formData, this.basic.tableName)
                    this.close()
                    return true
                  } else {
                    this.$message.error('请补全各级数据源')
                    return false
                  }
                })
              }
            }
            return true
          } else {
            return false
          }
        })
      },
      close() {
        this.editableTabs = []
        this.editableTabsValue = '1'
        this.formData = []
        this.$emit('close')
      },
      getParent(index) {
        return this.formData[index - 1].datas.map((item, ind) => {
          let label = this.fieldOptions.filter((opt) => {
            return opt.value === item.fieldName
          })
          return {
            label: label.length > 0 ? label[0].label : item.fieldName,
            value: item.fieldName
          }
        })
      },
      changeTable(val) {
        this.fieldOptions = []
        this.getFieldOption(val)
        this.formData.map((item)=>{
          item.datas.map((data)=>{
            data.fieldName = ''
            data.parent = ''
          })
        })
        this.editableTabsValue = '1'
      },
      changeTab(name, oldName) {
        if (name !== '1') {
          let change = false
          this.$refs.levelForm[Number(oldName) - 1].validate((valid) => {
            change = valid
            if (valid) {
              return true
            } else {
              return false
            }
          })
          return change
        } else {
          return true
        }
      },
      getTableName() {
        getAllFormName().then((res) => {
          if (res.code === 0) {
            this.tableOptions = res.data.map((item) => {
              return {
                label: item.formName,
                value: item.tableName
              }
            })
          }
        }).catch(e => console.log(e))
      },
      async getFieldOption(name) {
        let option = []
        await getTableColumn({
          tableName: name
        }).then((res) => {
          if (res.code === 0) {
            res.data.map((item) => {
              option.push({
                label: item.column,
                value: item.columnName
              })
            })
          }
        }).catch(e => console.log(e))
        this.fieldOptions = option
      },
      addTab() {
        let newTabName = this.tabIndex + '';
        this.editableTabs.push({
          name: newTabName
        });
        this.formData.push({
          datas: [{
            fieldName: '',
            parent: ''
          }],
          name: newTabName
        })
        this.editableTabsValue = newTabName;
        this.tabIndex++
      },
      removeTab(targetName) {
        let tabs = this.editableTabs;
        let activeName = this.editableTabsValue;
        if (activeName === targetName) {
          tabs.forEach((tab, index) => {
            if (tab.name === targetName) {
              let nextTab = tabs[index + 1] || tabs[index - 1];
              if (nextTab) {
                activeName = nextTab.name;
              }
              this.formData = this.formData.filter(data => data.name !== targetName)
            }
          });
        }
        this.editableTabsValue = activeName;
        this.editableTabs = tabs.filter(tab => tab.name !== targetName);
        this.tabIndex--
      },
      addDatasource() {
        this.formData[Number(this.editableTabsValue)-1].datas.push({
          fieldName: '',
          parent: ''
        })
      },
      removeDatasource(ind) {
        this.formData[Number(this.editableTabsValue)-1].datas.splice(ind, 1)
      },
      toChineseNumber(num) {
        return toChineseNum(num)
      }
    }
  }

</script>
